package com.netwit.database;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

import com.netwit.database.interceptor.SqlPrintInterceptor;

@Configuration
@MapperScan(basePackages = "com.netwit.mapper", sqlSessionTemplateRef = "manageSqlSessionTemplate")
public class DataSourceManageConfig {

    @Bean(name = "manageDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.manage")
    public DataSource getDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "manageSqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("manageDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        bean.setDataSource(dataSource);
        bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-config.xml"));
        bean.setPlugins(new Interceptor[] { new SqlPrintInterceptor() });
        return bean.getObject();
    }

    @Bean(name = "manageTransactionManager")
    public DataSourceTransactionManager getDataSourceTransactionManager(
            @Qualifier("manageDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "manageSqlSessionTemplate")
    public SqlSessionTemplate getSqlSessionTemplate(@Qualifier("manageSqlSessionFactory") SqlSessionFactory factory) {
        return new SqlSessionTemplate(factory);
    }

    public SqlPrintInterceptor sqlPrintInterceptor() {
        return new SqlPrintInterceptor();
    }
}
